using Microsoft.Extensions.DependencyInjection;
using Model.Core.Entity;
using Model.Core.Entity.Dbcontexts;
using Model.Core.Services;
using System.Collections.ObjectModel;

using Microsoft.EntityFrameworkCore;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Input;
namespace RobotPratolSolution.ViewModels
{
    public class SysSettingViewModel : ObservableObject
    { 
        private RobotInfo _selectedRobot;
        public RobotInfo SelectedRobot
        {
            get => _selectedRobot;
            set {  _selectedRobot = value; OnPropertyChanged(); }
}

      //  private ObservableCollection<MapInfo> _mapInfoList;
        private ObservableCollection<RobotType> _robotTypes = new ObservableCollection<RobotType>();

        public ObservableCollection<RobotType> RobotTypes
        {
            get => _robotTypes;
            set
            {
                _robotTypes = value;
                OnPropertyChanged();
            }
        }
        DbcontextBase _DbcontextBase { get; set; }
        public SysSettingViewModel()
        {
            _DbcontextBase = App.ServiceProvider.GetService(typeof(DbcontextBase)) as DbcontextBase;

            // 从数据库加载机器人类型
            RobotTypes = new ObservableCollection<RobotType>(_DbcontextBase.RobotType.ToList());
            
            LocalRobotInfo = App.ServiceProvider.GetService<LocalRobotInfo>();
            LoadMapInfo();
            LoadRobotInfo();
        }


        public LocalRobotInfo LocalRobotInfo { get; set; }
        private ObservableCollection<MapInfo> _mapInfoList = new();
        public ObservableCollection<MapInfo> MapInfoList
        {
            get => _mapInfoList;
            set { _mapInfoList = value; OnPropertyChanged(); }
        }

        //private ObservableCollection<RobotType> _robotTypes = new ObservableCollection<RobotType> { RobotType.CarryRobot, RobotType.StackRobot };
        //public ObservableCollection<RobotType> RobotTypes
        //{
        //    get => _robotTypes;
        //    set => Set(ref _robotTypes, value);
        //}
        public RelayCommand RefreshRobotSettingCommand => new RelayCommand(RefreshRobotInfoSetting);

        private void RefreshRobotInfoSetting()
        {
            LoadRobotInfo(); 
            LoadMapInfo();
        }

        //private DelegateCommand<RobotInfo> _deleteCommand;
        //public DelegateCommand<RobotInfo> DeleteCommand => _deleteCommand ??= new DelegateCommand<RobotInfo>(DeleteRobot);

        private void LoadMapInfo()
        {
            MapInfoList.Clear();
            foreach (var map in _DbcontextBase?.MapInfo.ToList())
            {
                MapInfoList.Add(new MapInfo
                {
                    MapId = map.MapId,
                    Name = map.Name
                });
            }
        }

        private void LoadRobotInfo()
        {
            // 初始化地图数据
            MapInfoList = new ObservableCollection<MapInfo>(_DbcontextBase?.MapInfo.ToList());
            RobotInfoList.Clear();

            foreach (var robot in _DbcontextBase?.RobotInfo.AsNoTracking().Include(r => r.MapInfo).ToList())
            {
                RobotInfoList.Add(new RobotInfo
                {
                    Id = robot.Id,
                    RobotId = robot.RobotId,
                    Name = robot.Name,
                    RobotType = robot.RobotType,
                    MapInfo = robot.MapInfo
                });
            }
        }

        private void DeleteRobot(RobotInfo robot)
        {
            var dbRobot = _DbcontextBase.RobotInfo.FirstOrDefault(r => r.RobotId == robot.RobotId);
            if (dbRobot != null)
            {
                _DbcontextBase.Remove(dbRobot);
                _DbcontextBase.SaveChanges();
System.Diagnostics.Debug.WriteLine($"数据库保存完成，受影响行数：{_DbcontextBase.SaveChanges()}");
var verifyEntity = _DbcontextBase.RobotInfo.AsNoTracking().Include(r => r.MapInfo).FirstOrDefault(r => r.Id == SelectedRobot.Id);
System.Diagnostics.Debug.WriteLine($"验证数据：MapID={verifyEntity?.MapInfo?.MapId} Name={verifyEntity?.MapInfo?.Name}");
            }
            RobotInfoList.Remove(robot);
        }
        private string _RobotName;

        public string RobotName
        {
            get => _RobotName;
            set{ _RobotName = value; OnPropertyChanged(); }
        }


        private string _RobotId;

        public string RobotId
        {
            get => _RobotId;
            set { _RobotId = value; OnPropertyChanged(); }
        }
        private string _Type;

        public string Type
        {
            get { return _Type; }
            set
            {
                if (_Type != value)
                {
                   _Type = value; OnPropertyChanged();
                
            }

            }
        }


        private string _RobotType;

        public string RobotType
        {
            get => _RobotType;
            set => _RobotType = value;
        }
        private string _MapName;
        public string MapName
        {
            get => _MapName;
            set { _MapName = value; OnPropertyChanged(); }
        }
        private string _MapId;
        public string MapId
        {
            get => _MapId;
            set { _MapId = value; OnPropertyChanged(); }
        }




        /// <summary>
        /// 获取机器人配置
        /// </summary>
        public void LoadRobotConfig()
        {
            RobotName = LocalRobotInfo.RobotName;
            RobotId = LocalRobotInfo.RobotId;
            Type = LocalRobotInfo.RobotType;
            MapId = LocalRobotInfo.MapId;
            MapName = LocalRobotInfo.MapName;

        }
        /// <summary>
        /// 应用机器人配置到当前app
        /// </summary>
        public void UseRobotConfig(RobotInfo robot)
        {
            LocalRobotInfo.UpdateRobotInfo(robot);
            
            // 清除旧订阅并重新订阅
            var mqClient = App.ServiceProvider.GetService<CloudMqClientCtrl>();
            var _MqTopics = App.ServiceProvider.GetService<GlobalData.MqTopics>();
            mqClient?.ClearAllSubscriptions();

            WeakReferenceMessenger.Default.Send("UpdateRobot");
            WeakReferenceMessenger.Default.Send("UpdateRobotType");
            Task.Delay(100).ContinueWith(A =>
                  {
                      LoadRobotConfig();

                    }
                );
        }


        /// <summary>
        /// 获取机器人配置
        /// </summary>
        public void UpdateRobotConfig(RobotInfo robot)
        {
            var existingEntity = _DbcontextBase.RobotInfo.Local.FirstOrDefault(e => e.Id == SelectedRobot.Id);
            if (existingEntity != null)
            {
                _DbcontextBase.Entry(existingEntity).CurrentValues.SetValues(SelectedRobot);
                                  // 显式更新MapInfo
                    existingEntity.MapInfo = SelectedRobot.MapInfo;
            }
            else
            {
                var dbEntity = _DbcontextBase.RobotInfo.AsNoTracking().FirstOrDefault(r => r.Id == SelectedRobot.Id);
                if (dbEntity != null)
                {
                    System.Diagnostics.Debug.WriteLine($"更新前 MapInfo: ID={dbEntity.MapInfo?.MapId} Name={dbEntity.MapInfo?.Name}");
                    _DbcontextBase.Entry(dbEntity).CurrentValues.SetValues(SelectedRobot);
  
                    dbEntity.MapInfo = _DbcontextBase.MapInfo.Find(SelectedRobot.MapInfo.Id);
                    _DbcontextBase.Entry(dbEntity).State = EntityState.Modified;
                    System.Diagnostics.Debug.WriteLine($"更新后 MapInfo: ID={SelectedRobot.MapInfo?.MapId} Name={SelectedRobot.MapInfo?.Name}");
                }
            }
            _DbcontextBase.SaveChanges();
            System.Diagnostics.Debug.WriteLine($"数据库保存完成，受影响行数：{_DbcontextBase.SaveChanges()}");
            var verifyEntity = _DbcontextBase.RobotInfo.AsNoTracking().Include(r => r.MapInfo).FirstOrDefault(r => r.Id == SelectedRobot.Id);
            System.Diagnostics.Debug.WriteLine($"验证数据：MapID={verifyEntity?.MapInfo?.MapId} Name={verifyEntity?.MapInfo?.Name}");
        }


        public ObservableCollection<RobotInfo> RobotInfoList { get; set; } = new ObservableCollection<RobotInfo>();


        public void AsyncRobotConfig(RobotInfo robot)
        {
            LocalRobotInfo.UpdateRobotInfo(robot);
            //Console.WriteLine($"robot.MapInfo.Id:{robot.MapInfo.Id}:robot.MapInfo.Name :{robot.MapInfo.Name}");
            Task.Delay(1000).ContinueWith(A =>
            LoadRobotConfig());
        }
    }
}


